<template>
  <!-- 搜索 -->
  <div class="good">
    <div class="mybody">
      <el-form class="myfind">
        <!-- 输入框 -->
        <el-form-item class="el1">
           <el-input label="请输入" placeholder="请输入您要搜索的关键字" v-model.lazy.trim="gjz" @input="onFind"/>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="onFind" class="b1" >搜索</el-button>
          <el-button type="warning" class="b2" @click="Reset">重置</el-button>
          <el-button type="success" class="b2" @click="addGoods">新增</el-button>
        </el-form-item>
      </el-form>

        <!-- 表单 -->
       <el-form class="mytable">
      <el-table :data="tableData" border stripe  style="width: 100%" ref="tableRef" align="center">
          
          <el-table-column  label="商品id" width="120" prop="id" />
          <el-table-column label="商品名称" width="180" prop="name"/>

          <el-table-column label="商品图片" width="120" prop="imgs" >
              <template #default="scope">
                  <img :src="`http://localhost:9191${scope.row.imgs}`" width="60" height="60">
              </template>
          </el-table-column>
          
          <el-table-column show-overflow-tooltip="true" label="商品描述" width="120" prop="description"/>
          <el-table-column label="折扣" width="120" prop="discount"/>
          <el-table-column label="销量" width="120" prop="sales"/>
          <el-table-column label="销售额（元）" width="130" prop="saleMoney"/>
          <el-table-column label="创建时间" width="200" prop="createTime"/>
            <el-table-column prop="recommend" label="推荐" width="100" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.recommend"
            @change="handleRecommendChange(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </template>
      </el-table-column>
          <el-table-column label="操作" width="200" >
          <template #default="scope">  
            <el-button type="primary" @click="change(scope.row)">修改</el-button>
            <el-button type="danger" @click="delGood(scope.row)">删除</el-button>
          </template>  
          </el-table-column>
      </el-table>
      </el-form>
    </div>
      <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        class="AddGood"
        v-model:current-page="currentPage2"
        v-model:page-size="pageSize2"
        :page-sizes="[5, 6, 7, 8]"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </div>


<!-- 新增/编辑 -->
    <el-dialog v-model="showGoods" :title="addTitle" width="50%">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        
        <el-form-item label="商品图片" prop="imgs">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9191/file/upload"
            :show-file-list="false"
            :on-success="changeImg"
          >
          <span>选择文件</span>
            <img v-if="form.imgs" :src="`http://localhost:9191${form.imgs}`" class="avatar" width="80">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input-number v-model="form.discount" :min="0" :max="1" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择分类">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          ></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="商品规格">
          <div class="specification-list">
            <el-tag
              v-for="(spec, index) in guige"
              :key="index"
              :closable="true"
              :disable-transitions="false"
              @close="removeSpecification(index)"
              style="margin-right: 10px; margin-bottom: 10px"
            >
              {{ spec.value }} - 价格: {{ spec.price }} - 库存: {{ spec.store }}
            </el-tag>
          </div>
          
          <div class="add-specification">
            <el-input v-model="newSpecification.value" placeholder="规格名称" style="width: 150px; margin-right: 10px;"></el-input>
            <el-input-number v-model="newSpecification.price" :min="0" :precision="2" :step="0.1" placeholder="价格" style="width: 120px; margin-right: 10px;"></el-input-number>
            <el-input-number v-model="newSpecification.store" :min="0" :precision="0" :step="1" placeholder="库存" style="width: 120px; margin-right: 10px;"></el-input-number>
            <el-button type="primary" @click="addSpecification">添加规格</el-button>
          </div>
        </el-form-item>
        <el-form-item label="推荐商品" prop="recommend">
          <el-switch v-model="form.recommend" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showGoods = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { inject, reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
const getid = ref([]);
const gjz = ref('');
const sousuo = ref('');
const tableData = ref([]);
const allData = ref([]); // 存储全量数据
const categoryList = ref([]); // 存储分类数据
const guige = ref([]); //规格

// 新规格临时数据
const newSpecification = ref({
  value: '',
  price: 0,
  store: 0
});

// 分页相关数据
const currentPage2 = ref(1);
const pageSize2 = ref(5);
const total = ref(0);


// 启动页面显示后端数据
const $axios = inject('$axios');

const loadAllData = () => {
  $axios.get(`http://localhost:9191/api/good/page?pageNum=1&pageSize=9999`).then((res) => {
    getid.value = res.data.records;
    console.log(guige.value);
    const requests = getid.value.map(item => {
      return $axios.get(`http://localhost:9191/api/good/${item.id}`);
    });
    Promise.all(requests).then(responses => {
      let data = responses.flatMap(response => response.data);
      // 按照 id 倒序排序
      data.sort((a, b) => b.id - a.id);
      allData.value = data;
      loadData();
    }).catch((error) => {
      console.log(error);
    });
  }).catch((error) => {
    console.log(error);
  });
};

const loadData = () => {
  if (!gjz.value) {
    const start = (currentPage2.value - 1) * pageSize2.value;
    const end = start + pageSize2.value;
    tableData.value = allData.value.slice(start, end);
    total.value = allData.value.length;
  } else {
    onFind();
  }
};

loadAllData();

// 加载分类数据
const loadCategoryData = () => {
  $axios.get('/api/category').then((res) => {
    if (res.code === '200') {
      categoryList.value = res.data;
    } else {
      ElMessage.error(res.message || '获取分类数据失败');
    }
  }).catch((error) => {
    console.log(error);
    ElMessage.error('获取分类数据失败，请稍后重试');
  });
};


// 搜索功能
const onFind = () => {
  if (!gjz.value) {
    loadData();
    return;
  }
  const filteredData = allData.value.filter(item => {
    return Object.values(item).some(value => {
      if (value) {
       return String(value).toLocaleLowerCase().includes(gjz.value.toLocaleLowerCase());
      }
      return false;
    });
  });
  tableData.value = filteredData;
  total.value = filteredData.length;
};

// 新增商品相关
const showGoods = ref(false)
const addTitle = ref('新增商品')
const formRef = ref(null)
const form = reactive({
  id: null,
  name: '',
  imgs: '',
  description: '',
  discount: 0,
  recommend: false,
  categoryId : ''
})

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  imgs: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
  discount: [{ required: true, message: '请输入折扣', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
})

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();

    // 根据是否有ID决定是新增还是修改
    const url = form.id ? `/api/good` : '/api/good';
    const method = form.id ? 'put' : 'post';
    
    const res = await $axios[method](url, form);
    
    if (res.code === '200') {
      // 获取商品ID
      const goodId = form.id || res.data;
      
      // 如果有规格数据，保存规格
      if (guige.value.length > 0) {
        try {
          // 为每个规格设置商品ID并确保数据类型正确
          const standards = guige.value.map(item => ({
            goodId: parseInt(goodId),
            value: item.value,
            price: parseFloat(item.price),
            store: parseInt(item.store)
          }));
          
          // 保存规格数据
          const standardRes = await $axios.post('/api/good/standard', standards, {
            params: { goodId: parseInt(goodId) }
          });
          
          if (standardRes.code !== '200') {
            ElMessage.warning('商品保存成功，但规格保存失败');
          }
        } catch (err) {
          console.error("保存规格失败:", err);
          ElMessage.warning('商品保存成功，但规格保存失败');
        }
      }
      
      ElMessage.success(form.id ? '商品更新成功' : '商品添加成功');
      showGoods.value = false;
      loadAllData();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (err) {
    console.error("操作失败:", err);
    ElMessage.error("操作失败，请稍后重试");
  }
};

// 编辑商品时加载规格数据
const change = (row) => {
  addTitle.value = '编辑商品';
  Object.assign(form, row);
  showGoods.value = true;
  
  // 清空规格数据
  guige.value = [];

  // 如果是编辑已存在的商品，加载其规格数据
  if (row.id) {
    $axios.get(`/api/good/standard/${row.id}`).then(res => {
      if (res.code === '200' && res.data) {
        // 将规格数据解析为对象数组
        try {
          let standardData = [];
          if (typeof res.data === 'string') {
            standardData = JSON.parse(res.data);
          } else if (Array.isArray(res.data)) {
            standardData = res.data;
          }
          
          if (standardData && standardData.length > 0) {
            guige.value = standardData.map(item => ({
              value: item.value,
              price: item.price,
              store: item.store
            }));
          }
        } catch (err) {
          console.error("解析规格数据失败:", err);
          ElMessage.warning("解析规格数据失败");
        }
      }
    }).catch(err => {
      console.error("获取商品规格失败:", err);
      ElMessage.error("获取商品规格失败，请稍后重试");
    });
  }
};

// 打开新增对话框
const addGoods = () => {
  addTitle.value = '新增商品'
  resetForm()
  showGoods.value = true
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.name = ''
  form.imgs = ''
  form.description = ''
  form.discount = 0
  form.recommend = false
  form.categoryId = ''
  // 清空规格数据
  guige.value = []
}

// 处理推荐状态变化
const handleRecommendChange = async (row) => {
  try {
    const res = await $axios.get('/api/good/recommend', {
      params: {
        id: row.id,
        isRecommend: row.recommend
      }
    })
    if (res.code === '200') {
      ElMessage.success('推荐状态更新成功')
    } else {
      ElMessage.error('推荐状态更新失败')
      row.recommend = !row.recommend
    }
  } catch (err) {
    console.error("更新推荐状态失败:", err)
    ElMessage.error("更新推荐状态失败，请稍后重试")
    row.recommend = !row.recommend
  }
}

// 图片上传成功
const changeImg = (res) => {
  if (res.code === '200') {
    form.imgs = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}


// 单个删除
const delGood = (row) => {
  const id = row.id;
  // 确认删除提示
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用后端接口删除商品
    $axios.delete(`http://localhost:9191/api/good/${id}`).then((res) => {
      if (res.code === '200') {
        ElMessage.success('商品删除成功！');
        // 重新加载数据
        loadAllData();
      } else {
        ElMessage.error(res.msg);
      }
    }).catch((error) => {
      ElMessage.error('删除商品失败，请稍后再试！');
      console.log(error);
    });
  }).catch(() => {
    // 用户取消删除操作
    ElMessage.info('已取消删除操作');
  });
};

// 重置功能
const Reset = () => {
  gjz.value = '';
  sousuo.value = '';
  loadData();
};

// 分页器事件处理函数
const handleSizeChange = (newSize) => {
  pageSize2.value = newSize;
  loadData();
};

const handleCurrentChange = (newPage) => {
  currentPage2.value = newPage;
  loadData();
};

// 添加规格
const addSpecification = () => {
  if (!newSpecification.value.value) {
    ElMessage.warning('请输入规格值');
    return;
  }
  guige.value.push({
    value: newSpecification.value.value,
    price: newSpecification.value.price,
    store: newSpecification.value.store
  });
  // 重置新规格输入
  newSpecification.value = {
    value: '',
    price: 0,
    store: 0
  };
};

// 删除规格
const removeSpecification = (index) => {
  guige.value.splice(index, 1);
};

// 初始化加载
onMounted(()=>{
    loadData();
    loadCategoryData()
});

</script>

<style scoped>
.good{
  padding: 2rem;
}
.el1{
  width: 15%;
}
.mytable{
  text-align: center;
}
.good  .mytable  :deep(button>span){
    color: white;
    font-family: "黑体";
}
.good  .myfind  :deep(button>span){
    color: white;
    font-family: "黑体";
}

.specification-list {
  margin-bottom: 15px;
}

.add-specification {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  margin-left: 10px;
}
</style>